package org.wu.framework.lazy.orm.database.jpa.repository.support.method;

import org.wu.framework.lazy.orm.core.persistence.conf.LazyTableEndpoint;
import org.wu.framework.lazy.orm.core.source.SqlSourceClass;
import org.wu.framework.lazy.orm.database.jpa.repository.core.LazyJpaEntityMetadata;
import org.wu.framework.lazy.orm.database.jpa.repository.enums.MethodName2SQLType;
import org.wu.framework.lazy.orm.database.jpa.repository.support.LazyRepositoryFactorySupport;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public abstract class AbstractLazyDynamicMethodSimpleQuerySupport
        implements LazyDynamicMethodSimpleQuerySupport {

    public static final String methodKeyBy = "_by_";
    public static final String methodKeyAnd = "_and_";
    public static final String methodKeyEndWithIn = "_in";

    /**
     * 是否支持方法转换程sql
     *
     * @param method 方法
     * @return 布尔类型
     */

    public Boolean supportMethodName2SQL(Method method) {

        String methodName = method.getName();
        boolean anyMatch = Arrays.stream(MethodName2SQLType.values())
                .anyMatch(methodName2SQLType -> methodName.startsWith(methodName2SQLType.getStartMethodNamePrefix()));

        if (anyMatch) {

            // 是否支持次方法
            List<MethodName2SQLType> methodName2SQLTypes = supportMethodName2SQLTypeList();

            return methodName2SQLTypes.stream().anyMatch(methodName2SQLType -> methodName.startsWith(methodName2SQLType.getStartMethodNamePrefix()));
        }
        return false;
    }


    /**
     * 支持的方法转换类型
     *
     * @return MethodName2SQLType 集合
     */
    protected abstract List<MethodName2SQLType> supportMethodName2SQLTypeList();


    /**
     * 通过方法名获取能够适配的 MethodName2SQLType
     *
     * @param methodName 方法名称
     * @return MethodName2SQLType
     */
    protected MethodName2SQLType getMethodName2SQLType(String methodName) {
        return Arrays.stream(MethodName2SQLType.values()).filter(methodName2SQLType -> methodName.startsWith(methodName2SQLType.getStartMethodNamePrefix())).findFirst().get();
    }

    /**
     * 获取 主表
     *
     * @param method 执行方法
     * @return 主表
     */
    protected String getMainTableName(Method method) {

        Class<?> lazyJpaRepositoryClass = method.getDeclaringClass();
        LazyJpaEntityMetadata<?, ?, ?> lazyJpaEntityMetadata = LazyRepositoryFactorySupport.getJpaMetadata(lazyJpaRepositoryClass);
        LazyTableEndpoint lazyTableEndpoint = SqlSourceClass.getInstance(lazyJpaEntityMetadata.getEntityClass()).getLazyTableEndpoint();
        return lazyTableEndpoint.getTableName();
    }

}
